from flask import Flask, render_template, request, redirect, url_for
import pandas as pd

app = Flask(__name__)

CSV_FILE = 'data.csv'


@app.route('/baimei')
def baimei_index():
    df = pd.read_csv(CSV_FILE)
    return render_template('index.html', data=df.to_dict(orient='records'))


@app.route('/add', methods=['GET', 'POST'])
def add_entry():
    if request.method == 'POST':
        name = request.form.get('name')
        age = request.form.get('age')
        email = request.form.get('email')

        df = pd.read_csv(CSV_FILE)
        new_row = pd.DataFrame({'Name': [name], 'Age': [age], 'Email': [email]})
        df = pd.concat([df, new_row], ignore_index=True)
        df.to_csv(CSV_FILE, index=False)

        return redirect(url_for('index'))
    return render_template('add.html')


@app.route('/baimei/edit/<int:index>', methods=['GET', 'POST'])
def edit_entry(index):
    df = pd.read_csv(CSV_FILE)
    if request.method == 'POST':
        df.at[index, 'Name'] = request.form.get('name')
        df.at[index, 'Age'] = request.form.get('age')
        df.at[index, 'Email'] = request.form.get('email')
        df.to_csv(CSV_FILE, index=False)

        return redirect(url_for('baimei_index'))

    entry = df.loc[index].to_dict()
    return render_template('edit.html', entry=entry, index=index)


if __name__ == '__main__':
    app.run(debug=True)